package com.lhn.spring5.jdkProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * jdk动态代理
 *
 * @author lhn
 * @date 2022/01/04 16:16
 * @since 1.0.0
 **/
public class JdkProxy {

    public static void main(String[] args) {
        Class[] interfaces = {UserDao.class};
        UserDaoImpl userDao = new UserDaoImpl();
        UserDao userDao1 = (UserDao) Proxy.newProxyInstance(JdkProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int add = userDao1.add(1, 1);
        System.out.println(add);
    }

}

class UserDaoProxy implements InvocationHandler {

    private Object obj;

    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("方法执行前运行。。。。" + method.getName() + ":传递的参数。。。" + Arrays.toString(args));
        Object res = method.invoke(obj, args);
        System.out.println("方法执行后运行。。。。" + method.getName() + ":传递的参数。。。" + Arrays.toString(args) + "---" + res);
        return res;
    }
}